import axios from 'axios';
import { Notification, MessageBox } from 'element-ui';
import store from '@/store';
import { getToken } from '@/utils/auth';

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 5000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    // Do something before request is sent

    // set content-type as application/json
    config.headers['Content-Type'] = 'application/json';

    if (store.getters.token) {
      // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
      config.headers['X-Token'] = getToken();
    }

    // transform form data as json string
    config.transformRequest = [function(data) {
      const requestBody = JSON.stringify({
        timestamp: new Date().getTime(),
        sign: 'nosign',
        data: data
      });
      return requestBody;
    }];
    return config;
  },
  error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  // response => response,
  /**
   * 下面的注释为通过在response里，自定义code来标示请求状态
   * 当code返回如下情况则说明权限有问题，登出并返回到登录页
   * 如想通过 xmlhttprequest 来状态码标识 逻辑可写在下面error中
   * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
   */
  response => {
    const res = response.data;
    if (res.code && res.code !== 0) {
      let msg;
      if (res.code === 90003) {
        msg = res.data;
      } else {
        msg = res.data;
      }
      Notification({
        title: res.msg,
        message: msg,
        type: 'error',
        duration: 5 * 1000
      });
      // 401:未登录; 10700:Token 已失效; 10701：Header缺失Token信息
      if (res.code === 401 || res.code === 10700 || res.code === 10701) {
        // 请自行在引入 MessageBox
        // import { Message, MessageBox } from 'element-ui'
        MessageBox.alert('你已被登出，请重新登录', '提示', {
          confirmButtonText: '确认',
          type: 'error'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload(); // 为了重新实例化vue-router对象 避免bug
          });
        });
      }
      return response;
    } else {
      return response;
    }
  },
  error => {
    console.log('err' + error); // for debug
    MessageBox({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
